<?php

namespace App\Store\Controllers\Goods;

use App\Store\Models\Basic\GoodsMetal;
use App\Store\Models\Goods\GoodsLog;
use App\Store\Models\Goods\GoodsStockinInfolist;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;


use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsBrand;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsContent;
use App\Store\Models\Basic\GoodsCraft;
use App\Store\Models\Basic\GoodsPricetype;
use App\Store\Models\Basic\GoodsStone;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Basic\Supply;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Models\OldMaterial\Stock;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Goods\Goods;
use Illuminate\Support\Facades\DB;
use App\Store\Validate\Goods\GoodsStockin as ValidateGoodsGoodsStockin;
use Mockery\Exception;

/**
 * 商品库存列表
 */
class GoodsStockListController extends Controller
{
    /**
     * 商品库存列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsStockList::getList($request);
        $iswarning = $request->iswarning;
        if ($request->withprice == 1 || $request->iswarning == 1) {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $cp_id = $accountinfo['cp_id'];
            foreach ($list['list'] as &$val) {
                if ($request->withprice == 1) {
                    if (!empty($val['goods_category'])) {
                        $good_price = GoodsGlodprice::where(['cp_id' => $cp_id, 'store_id' => $val['store_id'], 'goods_category_id' => $val['goods_category_id'], 'is_del' => 1])
                            ->select(['sales_price', 'sales_limit_min_price'])
                            ->where('date_str', '<=', date('Y-m-d'))->orderBy('date_str', 'desc')->first();
                        if ($val['goods_category']['is_gram'] == 1) {

                            $val['sales_price'] = empty($good_price) ? 0 : intval($good_price->sales_price);
                            $val['sales_limit_min_price'] = empty($good_price) ? 0 : intval($good_price->sales_limit_min_price);
                        } else {
                            $val['sales_price'] = 0;
                            $val['sales_limit_min_price'] = 0;
                            if($val['goods_category']['is_virtually']==1){
                                $val['sales_price'] = empty($good_price) ? 0 : intval($good_price->sales_price);
                                $val['sales_limit_min_price'] = empty($good_price) ? 0 : intval($good_price->sales_limit_min_price);
                            }
                        }
                    }
                }

                $iswarning == 1 && $val['iswarning'] = Goods::checkGoodsWarning($val);//1未预警，2预警
            }
        }

        foreach ($list['list'] as &$item){
            //补货金价
            $item['repllennish_costglod_price']=0;
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 根据主键查询库存信息
     */
    public function getinfobyid(Request $request)
    {
        $id = intval($request->id);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsStockList::with(['storeinfo', 'startstoreinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand'])->where(['cp_id' => $cp_id, 'id' => $id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 根据条码查询库存信息
     */
    public function getinfobysncode(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $goods_sn_code = $request->goods_sn_code;
        $store_id = $request->store_id ??0;

        $cp_id = $accountinfo['cp_id'];
        $info = GoodsStockList::with(['storeinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand'])
            ->where(['cp_id' => $cp_id, 'goods_sn_code' => $goods_sn_code, 'is_del' => 1])
            ->when($store_id > 0, function ($query) use ($store_id) {
                $query->where('store_id', $store_id);
            })
            ->first();
        $goods_metal_id =$info->goods_category['goods_metal_id']??0;

        $metalinfo=GoodsMetal::query()->where(['id'=>$goods_metal_id,'cp_id' => $cp_id,'is_del' => 1])->first();
        if(!empty($info)){
            $info->metalinfo= empty($metalinfo)?[]:$metalinfo->toArray();
        }

        $info =empty($info)?[]: $info->toArray();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    public function getinfobysncodemore(Request $request)
    {
        $goods_sn_code_list = $request->goods_sn_code_list;
        $goods_sn_code_list = $goods_sn_code_list ? (is_array($goods_sn_code_list) ? $goods_sn_code_list : (explode(',', $goods_sn_code_list))) : [];
        if (count($goods_sn_code_list) <= 0) {
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => []]]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $cp_id = $accountinfo['cp_id'];
        if (!in_array($accountinfo['type'], [1, 2])) { //权限控制
            return response()->json(['code' => '001', 'msg' => '无权限，请使用门店端进行审核']);
        }
        $store_id = intval($accountinfo['store_ids']);
        $metalList=GoodsMetal::query()->where(['cp_id' => $cp_id,'is_del' => 1])
            ->get()
            ->pluck(null,'id')
            ->toArray();

        $list = GoodsStockList::with(['storeinfo', 'startstoreinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand'])
            ->where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $store_id])->whereIn('goods_sn_code', $goods_sn_code_list)
            ->get()
            ->toArray();

        foreach ($list as $item){
            $goods_metal_id =$item['goods_category']['goods_metal_id']??0;
            $item['metalinfo'] =$metalList[$goods_metal_id]?? [];
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => $list]]);
    }


    public function downdownload(Request $request)
    {
        if ($request->type == 1) {
            $row = [['原条码', '新条码']];
            $options = [];
            $datawith = [
                'A' => '25',
                'B' => '25',
            ];
            $filename = '条码修改模板_' . time() . '.xlsx';
            return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
        } else {
            $store_id = intval($request->store_id);
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $cp_id = $accountinfo['cp_id'];
            $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
            if (!$storeinfo) {
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }
            //获取门店商品类别
            $row = [[
                '条码', '入库日期', '供应商', '款式', '品名', '商品类别', '数量', '克销工费', '标签价', '件销工费', '件重', '金重', '含量',
                '成本金价', '件成本工费', '克成本工费', '单件成本', '工艺', '圈号', '款号', '宝石费1', '宝石费2', '附加费1', '附加费2', '品牌', '证书号', //Z
                'GIA证书号', '证书费', '主石重', '主石数', '副石重', '副石数', '颜色', '净度', '主石值', '副石值', '切工', '价格类型', '石料材质', '采购时间', '支付方式', '应付账款', '备注'
                , '总金重', '总件重', '是否一码多货'
            ]]; //Aq
            $options = [
                'C' => Supply::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('supply_name')->toArray(),
                'D' => GoodsStyle::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('style_name')->toArray(),
                'F' => GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $store_id])->limit(10)->pluck('category_name')->toArray(),
                'M' => GoodsContent::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('content_name')->toArray(),
                'R' => GoodsCraft::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('craft_name')->toArray(),
                'Y' => GoodsBrand::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('brand_name')->toArray(),
                'AL' => GoodsPricetype::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('pricetype_name')->toArray(),
                'AM' => GoodsStone::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('stone_name')->toArray(),
                'AO' => PaytypeList::where(['cp_id' => $cp_id, 'is_del' => 1])->pluck('paytype_name')->toArray(),
                'AT' => ['否', '是']

            ];
            $datawith = [
                'A' => '25', 'M' => '15',
            ];
            $filename = '批量修改商品导入模板_' . time() . '.xlsx';
            return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
        }

    }


    /**
     * 批量修改--条码
     */
    public function doposteditbysncode(Request $request)
    {
        $store_id = intval($request->store_id);
        $filepathname = $request->filepathname;

        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $cp_id = $accountinfo['cp_id'];

            $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
            if (!$storeinfo) {
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }

            $order_sncode = StoreCommon::createOrderSn();
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    if (count($val) != 2) {
                        return response()->json(['code' => '001', 'msg' => '导入数据格式错误']);
                    }
                    continue;
                }

                $newGoods = GoodsStockList::query()
                    ->where(['cp_id' => $cp_id, 'goods_sn_code' => trim($val[1]), 'is_del' => 1])
                    ->first();

                if (!empty($newGoods)) {
                    return response()->json(['code' => '001', 'msg' => '条码' . $val[1] . '已存在']);
                }

                $infolist = GoodsStockList::query()
                    ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'goods_sn_code' => $val[0], 'is_del' => 1])
                    ->get()
                    ->toArray();//可能存在货物相同的可能，调拨入库的货物
                foreach ($infolist as $info) {
                    GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $val[0], 'id' => $info['id'],'is_del' => 1])->update(['goods_sn_code' => strval($val[1]),'update_at'=>time()]);
                    $newinfo = $info;
                    $newinfo['goods_sn_code'] = $val[1];
                    //日志
                    Goods::changeGoodsLog($request, $order_sncode, $info, json_encode($info), json_encode($newinfo));
                }
            }
            return response()->json(['code' => '000', 'msg' => '条码修改成功']);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }


    /**
     * 批量修改商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function doposteditbygoods(Request $request)
    {
        $store_id = intval($request->store_id);
        $filepathname = $request->filepathname;


        try {
            if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
                $file = storage_path() . $filepathname;
                $data = Excel::toArray(null, $file)[0];
                // 获取数组的第一行和最后一行
                $first = reset($data)[0] ?? '';
                $end = end($data)[0] ?? '';
                if (!empty($first) && $first == '库存实时明细') {
                    unset($data[0], $data[1]);
                }

                if (!empty($end) && $end == '合计') {
                    array_pop($data);
                }

                $data = array_values($data);

                $accountinfo = StoreCommon::getCurrentAccountinfo($request);
                $cp_id = $accountinfo['cp_id'];

                $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();

                if (!$storeinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                }
                $order_sncode = StoreCommon::createOrderSn();

                $tabCount =count(array_filter($data[0]));

                foreach ($data as &$it){
                    $it= array_slice($it, 0, $tabCount);

                }

                // 获取表头并映射到列索引
                $header = array_shift($data);

               // print_r($header);exit;
                $columnMap = array_flip($header);
                // 数据库字段对应表头
                $requiredColumns = [
                    'goods_sn_code' => '条码',
                    'stockin_at' => '入库日期',
                    'supply_id' => '供应商',
                    'goods_style_id' => '款式',
                    'goods_name' => '品名',
                    'goods_category_id' => '商品类别',
                    'count' => '数量',
                    'gramprice_fee' => '克销工费',
                    'label_price' => '标签价',
                    'pieceprice_fee' => '件销工费',
                    'piece_weight' => '件重',
                    'netglod_weight' => '金重',
                    'goods_content_id' => '含量',
                    'costglod_price' => '成本金价',
                    'costpiece_fee' => '件成本工费',
                    'costgram_fee' => '克成本工费',
                    'piececost_fee' => '单件成本',
                    'goods_craft_id' => '工艺',
                    'c_no' => '圈号',
                    's_no' => '款号',
                    'gemstone_fee1' => '宝石费1',
                    'gemstone_fee2' => '宝石费2',
                    'add_fee1' => '附加费1',
                    'add_fee2' => '附加费2',
                    'goods_brand_id' => '品牌',
                    'cf_no' => '证书号',
                    'cf_no_gia' => 'GIA证书号',
                    'cf_fee' => '证书费',
                    'main_stone_weigth' => '主石重',
                    'main_stone_count' => '主石数',
                    'other_stone_weigth' => '副石重',
                    'other_stone_count' => '副石数',
                    'color' => '颜色',
                    'clarity' => '净度',
                    'main_stone_val' => '主石值',
                    'other_stone_val' => '副石值',
                    'cut' => '切工',
                    'goods_pricetype_id' => '价格类型',
                    'goods_stone_id' => '石料材质',
                    'procure_at' => '采购时间',
                    'paytype_id' => '支付方式',
                    'paymoney' => '应付账款',
                    'remark' => '备注',
                    'total_piece_weight' => '总件重',
                    'total_netglod_weight' => '总金重',
                    'is_code_more' => '是否一码多货'
                ];

                $tabArr=[];
                foreach ($requiredColumns as $str){
                    $tabArr[]=$str;
                }



//
//                foreach ($header as $head){
//                    if(!in_array($head,$tabArr)){
//                        return response()->json(['code' => '001', 'msg' => '导入的数据模版不正确，请使用正确的模版导入']);
//                    }
//                }



                $dataMap = [];
                // 检查必需的列是否存在
                foreach ($requiredColumns as $field => $col) {
                    $key = $columnMap[$col] ?? '';
                    if ($key !== '') {
                        $dataMap[$key] = $field;
                    }

                }


                if (empty($data)) {
                    return response()->json(['code' => '001', 'msg' => '导入的数据不能为空']);
                }
                foreach ($data as $value) {
                    $stock = [];
                    $error_msg = [];
                    foreach ($value as $k => $v) {
                        $key = $dataMap[$k] ?? '';
                        if ($key == 'goods_sn_code' && empty($v)) {
                            return response()->json(['code' => '001', 'msg' => '缺少必要的商品条码列']);
                        }

                        $stock[$key] = trim($v);
                    }

                    $stockKeys = array_keys($stock);


                    $list = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $store_id, 'goods_sn_code' => $stock['goods_sn_code'] ?? '', 'is_del' => 1])->get()->toArray();
                    foreach ($list as $k=>$info) {
                        // 增加判断：如果商品数量小于等于0，不能被修改
                        if ($info['count'] <= 0) {
                            $error_msg[] = '商品条码[' . $stock['goods_sn_code'] . ']为售出状态，不能修改';
                            continue;
                        }
                        if (empty($info['goods_style_id']) && !isset($stock['goods_style_id'])) {
                            return response()->json(['code' => '001', 'msg' => '款式不能为空']);
                        }
                        if (empty($info['goods_name'])  && !isset($stock['goods_name'])) {
                            return response()->json(['code' => '001', 'msg' => '品名不能为空']);
                        }
                        if (empty($info['goods_category_id'])&&!empty($stock['goods_category_id'])) {
                            return response()->json(['code' => '001', 'msg' => '类别不能为空']);
                        }


                        $goods_style_id = intval(GoodsStyle::where(['cp_id' => $cp_id, 'is_del' => 1, 'style_name' => $stock['goods_style_id'] ?? ''])->value('id'));
                        $goods_style_id =$goods_style_id>0?$goods_style_id:$info['goods_style_id'];

                        $goods_category_id =intval(GoodsCategory::where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1, 'category_name' => $stock['goods_category_id'] ?? ''])->value('id'));
                        $goods_category_id =$goods_category_id>0?$goods_category_id:($info['goods_category_id']??0);
                        $goods_name =!empty($stock['goods_name'])?$stock['goods_name']:$info['goods_name'];
                        if(empty($goods_category_id)){
                            return response()->json(['code' => '001', 'msg' => '类别不存在']);
                        }


                        $item = [
                            'goods_sn_code' => $stock['goods_sn_code'],
                            'cp_id' => $cp_id,
                            'store_id' => $store_id,
                            'goods_name' => $goods_name,
                            'goods_style_id' => $goods_style_id,
                            'goods_category_id' => $goods_category_id,
                            'stockin_at' => strtotime($stock['stockin_at'] ?? 0),
                            'supply_id' => intval(Supply::query()->where(['cp_id' => $cp_id, 'is_del' => 1, 'supply_name' => $stock['supply_id'] ?? ''])->value('id')),
                            'count' => intval($stock['count'] ?? 0),
                            'gramprice_fee' => intval((double)($stock['gramprice_fee'] ?? 0) * 100),
                            'label_price' => intval((double)($stock['label_price'] ?? 0) * 100),
                            'pieceprice_fee' => intval((double)($stock['pieceprice_fee'] ?? 0) * 100),
                            'piece_weight' => doubleval($stock['piece_weight'] ?? 0),
                            'netglod_weight' => doubleval($stock['netglod_weight'] ?? 0),
                            'goods_content_id' =>intval(GoodsContent::where(['cp_id' => $cp_id, 'is_del' => 1, 'content_name' => $stock['goods_content_id'] ?? ''])->value('id')),
                            'costglod_price' => empty($stock['costglod_price'])? 0:intval(round(($stock['costglod_price'] ?? 0),2) * 100),
                            'costpiece_fee' => empty($stock['costpiece_fee'])? 0:intval((double)($stock['costpiece_fee'] ?? 0) * 100),
                            'costgram_fee' => empty($stock['costgram_fee'])? 0:intval((double)($stock['costgram_fee'] ?? 0) * 100),
                            'piececost_fee' => empty($stock['piececost_fee'])? 0 :intval((double)($stock['piececost_fee'] ?? 0) * 100),
                            'goods_craft_id' => intval(GoodsCraft::where(['cp_id' => $cp_id, 'is_del' => 1, 'craft_name' => $stock['goods_craft_id'] ?? ''])->value('id')),
                            'c_no' => (string)($stock['c_no'] ?? ''),
                            's_no' => (string)($stock['s_no'] ?? ''),
                            'gemstone_fee1' => intval((double)($stock['gemstone_fee1'] ?? 0) * 100),
                            'gemstone_fee2' => intval((double)($stock['gemstone_fee2'] ?? 0) * 100),
                            'add_fee1' => intval((double)($stock['add_fee1'] ?? 0) * 100),
                            'add_fee2' => intval((double)($stock['add_fee2'] ?? 0) * 100),
                            'goods_brand_id' => intval(GoodsBrand::where(['cp_id' => $cp_id, 'is_del' => 1, 'brand_name' => $stock['goods_brand_id'] ?? ''])->value('id')),
                            'cf_no' => (string)($stock['cf_no'] ?? ''),
                            'cf_no_gia' => (string)($stock['cf_no_gia'] ?? ''),
                            'cf_fee' => intval((double)($stock['cf_fee'] ?? 0) * 100),
                            'main_stone_weigth' => doubleval($stock['main_stone_weigth'] ?? 0),
                            'main_stone_count' => intval($stock['main_stone_count'] ?? 0),
                            'other_stone_weigth' => doubleval($stock['other_stone_weigth'] ?? 0),
                            'other_stone_count' => intval($stock['other_stone_count'] ?? 0),
                            'color' => (string)($stock['color'] ?? ''),
                            'clarity' => (string)($stock['clarity'] ?? ''),
                            'main_stone_val' => (string)($stock['main_stone_val'] ?? ''),
                            'other_stone_val' => (string)($stock['other_stone_val'] ?? ''),
                            'cut' => (string)($stock['cut'] ?? ''),
                            'goods_pricetype_id' => intval(GoodsPricetype::where(['cp_id' => $cp_id, 'is_del' => 1, 'pricetype_name' => $stock['goods_pricetype_id'] ?? ''])->value('id')),
                            'goods_stone_id' => intval(GoodsStone::where(['cp_id' => $cp_id, 'is_del' => 1, 'stone_name' => $stock['goods_stone_id'] ?? ''])->value('id')),
                            'procure_at' => strtotime($stock['procure_at'] ?? ''),
                            'paytype_id' => intval(PaytypeList::where(['cp_id' => $cp_id, 'is_del' => 1, 'paytype_name' => $stock['paytype_id'] ?? ''])->value('id')),
                            'paymoney' => intval((double)($stock['paymoney'] ?? 0) * 100),
                            'remark' => (string)($stock['remark'] ?? ''),
                            'total_piece_weight' => doubleval($stock['total_piece_weight'] ?? 0),
                            'total_netglod_weight' => (doubleval($stock['total_netglod_weight'] ?? 0)),
                            'is_code_more' => ($stock['is_code_more'] ?? '') == '是' ? 2 : 1
                        ];



                        $Validate = new ValidateGoodsGoodsStockin('editimport');
                        if (!$Validate->check($item)) {
                            $error_msg[] = '第' . ((int)$k + 1) . '行,'.$Validate->getError();
                        } else {


                            if(!empty($stockKeys)){
                                foreach ($item as $ik=>$v){
                                    if(!in_array($ik,$stockKeys)){
                                        unset($item[$ik]);
                                    }
                                }
                            }


//                            foreach ($item as $key => &$val) {
//                                if (!in_array($key, $dataMap) && !in_array($key, ['cp_id', 'store_id','goods_category_id'])) {
//                                    unset($item[$key]);
//                                }
//                            }


                            $item = array_merge($info,$item);


                            $category = GoodsCategory::query()
                                ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
                                ->where('id', $item['goods_category_id'])
                                ->first();
                            $category = empty($category) ? [] : $category->toArray();

                            $is_gram = $category['is_gram'] ?? 0;

                            $label_price = $item['label_price'] ?? 0;//标签价
                            $piece_weight = isset($item['piece_weight']) ? ($item['piece_weight'] ?? 0) : $info['piece_weight'];
                            $netglod_weight = isset($item['netglod_weight']) ? $item['netglod_weight'] : $info['netglod_weight'];//金重
                            $total_netglod_weight = isset($item['total_netglod_weight']) ? $item['total_netglod_weight'] : $info['total_netglod_weight']; //总金重
                            $is_code_more = isset($item['is_code_more']) ? $item['is_code_more'] : $info['is_code_more'];//是否一码多货
                            $pricetype = isset($item['pricetype']) ? $item['pricetype'] : $info['pricetype'];
                            //克成本工费
                            $costgram_fee = $item['costgram_fee'] ?? 0;
                            //件成本工费
                            $costpiece_fee = $item['costpiece_fee'] ?? 0;
                            //单件成本
                            $piececost_fee = $item['piececost_fee'] ?? 0;
                            //成本金价
                            $costglod_price = isset($item['costglod_price']) ? $item['costglod_price'] : $info['costglod_price'];
                            $count = isset($item['count']) ? $item['count'] : $info['count'];
                            $odds = isset($item['odds']) ? $item['odds'] : $info['odds'];

                            if ($is_code_more == 2) {
                                if ($total_netglod_weight <= 0) {
                                    $error_msg[] = '第' .((int)$key + 2) . '行,一码多货商品总金重必填';
                                } else {
                                    //是一码多货的商品的 总成本=成本金价*总金重
                                    $total_cost_fee = $costglod_price * $total_netglod_weight;
                                }

                            } else {
                                // 非一码多货，总金重 =金重*数量
                                $total_netglod_weight = $netglod_weight * $count;
                                //非一码多货，总件重 =件重*数量
                                $total_piece_weight = $piece_weight * $count;

                                if ($is_gram == 1) {
                                    //类别是素金和是克算
                                    //总成本 = （成本金价*总金重+克成本工费*总金重）+件成本工费*数量
                                    $total_cost_fee = ($costglod_price * $total_netglod_weight + $costgram_fee * $total_netglod_weight) + $costpiece_fee * ($val['count'] ?? 0);
                                } else {
                                    if($piececost_fee<=0){
                                        //按克成本工费:单件成本=(成本金价+克成本工费)*件重
                                        $canFee = $costgram_fee > 0 ? bcmul(($costgram_fee + $costglod_price), $piece_weight, 2) : 0;
                                        // 按件成本工费(默认):单件成本=成本金价*件重+件成本工费
                                        $pieceFee = $costpiece_fee > 0 ? bcadd($piece_weight * $costglod_price, $costpiece_fee, 2) : 0;

                                        if ($costgram_fee > 0 && $costpiece_fee > 0) {
                                            $piececost_fee = $pieceFee;
                                        } else {
                                            $piececost_fee = $canFee > 0 ? $canFee : $pieceFee;
                                        }
                                    }

                                    if ($label_price <= 0) {
                                        //1单件成本、2重量
                                        if ($pricetype == 1) {
                                            //标签价
                                            $label_price = (bcmul($piececost_fee, ($odds ?? 1), 2)) * 100;
                                        } elseif ($pricetype == 2) {
                                            //标签价=件重*倍率（倍率手动输入）
                                            $label_price = bcmul($piece_weight * ($odds ?? 1), 100);
                                        }
                                    }

                                    //总成本 = 单件成本*数量
                                    $total_cost_fee = ($piececost_fee * $count);
                                }


                            }
                        }
                        $item['count'] = $count??0;
                        $item['piececost_fee'] = $piececost_fee;
                        $item['label_price'] = $label_price;
                        $item['piece_weight'] = $piece_weight;

                        $item['goods_name'] = $goods_name;
                        $item['stockin_at'] =  $info['stockin_at']>0?$info['stockin_at']:($item['stockin_at']??time());
                        $item['goods_category_id'] = $goods_category_id;
                        $item['goods_style_id'] = $goods_style_id;
                        $item['total_netglod_weight'] = $total_netglod_weight??0;
                        $item['total_piece_weight'] = $total_piece_weight??0;
                        $item['total_cost_fee'] =$total_cost_fee ?? 0;

                        if (empty($item)) {
                            $error_msg[] = '批量修改的数据不能为空';
                        }else{
                            $item['update_at'] =time();
                        }



                        if (!empty($error_msg)) {
                            return response()->json(['code' => '001', 'msg' => '批量修改的数据报错，' . implode(',', $error_msg)]);
                        }

                        info('批量修改商品',$item);
                        try {
                            DB::beginTransaction();

                            GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $item['goods_sn_code'], 'id' => $info['id'],'is_del' => 1])->update($item);
                            $count = $info['count'] - ($item['count']??0);
                            Goods::goodsLog($request, 0, intval($info['store_id']), $item, intval($count), 4, '');
                            Goods::changeGoodsLog($request, $order_sncode, $info, json_encode($info), json_encode($item));
                            DB::commit();
                        } catch (\Exception $e) {
                            DB::rollBack();
                            return response()->json(['code' => '001', 'msg' => '处理失败: ' . $e->getFile().$e->getLine() . '错误描述' . $e->getMessage()]);
                        }
                    }
                }
                if(!empty($error_msg))
                {
                    return response()->json(['code' => '001', 'msg' => '批量修改的数据报错，' . implode(',', $error_msg)]);
                }
                return response()->json(['code' => '000', 'msg' => '批量修改成功']);
            } else {
                return response()->json(['code' => '001', 'msg' => '文件不存在']);
            }

        }catch (\Exception $e){
            info('商品信息错误',$e->getMessage());
            return response()->json(['code' => '001', 'msg' => '商品信息错误']);
        }


    }


    /**
     * 删除
     */
    public function dopostdel(Request $request)
    {
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $infolist = GoodsStockList::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', $ids)->get()->toArray();
        if (count($infolist) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $goodsStock = GoodsStockList::query()->where(['cp_id' => $cp_id,'is_del' => 1])->whereIn('id', $ids)->get()->toArray();
        $data = [];
        // 记录删除日志的流水
        if (!empty($goodsStock)) {
            foreach ($goodsStock as $goods) {
                $data[] = [
                    'cp_id' => $cp_id,
                    'start_store_id' => $goods['store_id'],
                    'target_store_id' => $goods['store_id'],
                    'goods_img' => isset($goods['goods_img']) ? $goods['goods_img'] : '',
                    'goods_sn_code' => $goods['goods_sn_code'],
                    'goods_name' => $goods['goods_name'],
                    'goods_category_id' => $goods['goods_category_id'],
                    'cf_no' => isset($goods['cf_no']) ? $goods['cf_no'] : '',
                    'count' => $goods['count'],
                    'piece_weight' => $goods['netglod_weight'],
                    'netglod_weight' => $goods['netglod_weight'],
                    'label_price' => $goods['label_price'],
                    'piececost_fee' => $goods['piececost_fee'],
                    'log_type' => 99,
                    'with_sn_code' => '',
                    'stockin_at' => $goods['stockin_at'],
                    'create_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                    'update_at' => time(),
                    'is_code_more' => $goods['is_code_more'],
                ];
            }
        }
        if (!empty($data)) {
            GoodsLog::query()->insert($data);
        }

        GoodsStockList::where(['cp_id' => $cp_id, 'is_del' => 1])->whereIn('id', $ids)->update(['is_del' => 2, 'del_at' => time()]);

        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }


    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'store_id', 'goods_sn_code', 'goods_img', 'pricetype', 'odds', 'goods_name', 'goods_style_id', 'goods_category_id', 'stockin_at', 'supply_id', 'count', 'gramprice_fee', 'label_price',
            'pieceprice_fee', 'piece_weight', 'netglod_weight', 'content', 'costglod_price', 'costpiece_fee', 'costgram_fee', 'piececost_fee', 'goods_craft_id', 'c_no', 's_no',
            'gemstone_fee1', 'gemstone_fee2', 'add_fee1', 'add_fee2', 'goods_brand_id', 'cf_no', 'cf_no_gia', 'cf_fee', 'main_stone_weigth', 'main_stone_count', 'other_stone_weigth',
            'other_stone_count', 'color', 'clarity', 'main_stone_val', 'other_stone_val', 'cut', 'goods_pricetype_id', 'goods_stone_id', 'procure_at', 'paytype_id', 'paymoney', 'remark', 'total_piece_weight', 'total_netglod_weight', 'is_code_more', 'goods_content_id'
        ]);

        $Validate = new ValidateGoodsGoodsStockin();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $storeinfo = SiteStore::where(['id' => $req_data['store_id'], 'cp_id' => $cp_id])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $isexist = GoodsStockList::where(['cp_id' => $cp_id, 'store_id' => $req_data['store_id'], 'goods_sn_code' => $req_data['goods_sn_code'], 'is_del' => 1])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '条码：' . $req_data['goods_sn_code'] . '已存在']);
        }
        $categoryinfo = GoodsCategory::where(['cp_id' => $cp_id, 'store_id' => $req_data['store_id'], 'is_del' => 1, 'id' => $req_data['goods_category_id']])->first();
        if (!$categoryinfo) {
            return response()->json(['code' => '001', 'msg' => '无效分类参数']);
        }
        if ($req_data['is_code_more'] == 2 && $categoryinfo->is_gram == 2) {
            return response()->json(['code' => '001', 'msg' => '该分类为非克重商品，不可选择一码多货']);
        }


        $infodata = $req_data;
        $infodata['stockin_at'] = (isset($req_data['stockin_at']) && !empty($infodata['stockin_at'])) ? strtotime($infodata['stockin_at']) : time();
        $infodata['procure_at'] = (isset($req_data['procure_at']) && !empty($infodata['procure_at'])) ? strtotime($infodata['procure_at']) : time();
        $infodata['create_at'] = time();
        $infodata['start_stockin_store_id'] = $req_data['store_id'];
        $infodata['total_piece_weight'] = isset($infodata['total_piece_weight']) ? $infodata['total_piece_weight'] : 0;
        $infodata['total_netglod_weight'] = isset($infodata['total_netglod_weight']) ? $infodata['total_netglod_weight'] : 0;
        if ($req_data['is_code_more'] == 2) {
            // $infodata['total_cost_fee'] = bcmul((string)($infodata['costgram_fee'] + $infodata['costglod_price']), $infodata['total_netglod_weight'], 0) + $infodata['costpiece_fee'] * $infodata['count'];

            if ($infodata['total_netglod_weight'] <= 0) {
                return response()->json(['code' => '001', 'msg' => '一码多货必须输入总金重']);
            }
            $infodata['total_cost_fee'] = bcmul((float)($infodata['costglod_price'] ?? 0), ($infodata['total_netglod_weight'] ?? 0));

        } else {
            // 总件重

            $infodata['total_piece_weight'] = isset($infodata['piece_weight']) ? doubleval((float)$infodata['piece_weight'] * $infodata['count']) : 0;
            // 总金重
            $infodata['total_netglod_weight'] = isset($infodata['netglod_weight']) ? doubleval((float)$infodata['netglod_weight'] * $infodata['count']) : 0;
            $is_gram = GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $req_data['store_id'], 'id' => $infodata['goods_category_id']])->value('is_gram');


            if ($infodata['total_netglod_weight'] <= 0 || $infodata['netglod_weight'] <= 0) {
                return response()->json(['code' => '001', 'msg' => '总金重以及金重不可小于0']);
            }
            if ($is_gram == 1) {
                $infodata['total_cost_fee'] = bcmul((string)($infodata['costgram_fee'] + $infodata['costglod_price']), $infodata['total_netglod_weight'], 0) + $infodata['costpiece_fee'] * $infodata['count'];

            } else {
                if ($infodata['total_piece_weight'] < 0 || $infodata['piece_weight'] < 0) {
                    return response()->json(['code' => '001', 'msg' => '总件重以及件重不可小于0']);
                }

                $infodata['total_cost_fee'] = $infodata['piececost_fee'] * $infodata['count'];
            }


        }
        //处理数据类型
        $infodata['cp_id'] = $cp_id;
        foreach ($infodata as $key => $val) {
            if ($val == '' || $val == 0) {
                unset($infodata[$key]);
            }
        }

        DB::beginTransaction();
        try {
            (new Goods())->stockInAdd($infodata,$accountinfo,2);
            $id = GoodsStockList::create($infodata)->id;
            $infdata = GoodsStockList::where(['cp_id' => $cp_id, 'id' => $id,'is_del' => 1])->first()->toArray();
            Goods::goodsLog($request, 0, intval($infodata['store_id']), $infodata, intval($infodata['count']), 1, '');
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '商品添加失败'.$e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '商品添加成功']);
    }

    /**
     * 编辑---库存数据编辑
     */
    public function dopostinfoedit(Request $request)
    {
        $req_data = $request->only([
            'id', 'goods_sn_code', 'goods_img', 'pricetype', 'odds', 'goods_name', 'goods_style_id', 'goods_category_id', 'stockin_at', 'supply_id', 'count', 'gramprice_fee', 'label_price',
            'pieceprice_fee', 'piece_weight', 'netglod_weight', 'content', 'costglod_price', 'costpiece_fee', 'costgram_fee', 'piececost_fee', 'goods_craft_id', 'c_no', 's_no',
            'gemstone_fee1', 'gemstone_fee2', 'add_fee1', 'add_fee2', 'goods_brand_id', 'cf_no', 'cf_no_gia', 'cf_fee', 'main_stone_weigth', 'main_stone_count', 'other_stone_weigth',
            'other_stone_count', 'color', 'clarity', 'main_stone_val', 'other_stone_val', 'cut', 'goods_pricetype_id', 'goods_stone_id', 'procure_at', 'paytype_id', 'paymoney', 'remark'
            , 'total_piece_weight', 'total_netglod_weight', 'is_code_more', 'goods_content_id'
        ]);

        $Validate = new ValidateGoodsGoodsStockin('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = GoodsStockList::where(['cp_id' => $cp_id, 'id' => $req_data['id'], 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $isexist = GoodsStockList::where('id', '<>', $req_data['id'])->where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_sn_code' => $req_data['goods_sn_code'], 'is_del' => 1])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '条码：' . $req_data['goods_sn_code'] . '已存在']);
        }

        $categoryinfo = GoodsCategory::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'is_del' => 1, 'id' => $req_data['goods_category_id']])->first();
        if (!$categoryinfo) {
            return response()->json(['code' => '001', 'msg' => '无效分类参数']);
        }
        if ($req_data['is_code_more'] == 2 && $categoryinfo->is_gram == 2) {
            return response()->json(['code' => '001', 'msg' => '该分类为非克重商品，不可选择一码多货']);
        }


        $infodata = $req_data;

        $infodata['stockin_at'] = (isset($req_data['stockin_at']) & !empty($infodata['stockin_at'])) ? strtotime($infodata['stockin_at']) : $info['stockin_at'];
        $infodata['procure_at'] = (isset($req_data['procure_at']) && !empty($infodata['procure_at'])) ? strtotime($infodata['procure_at']) : $info['stockin_at'];
        $checkeys=[
            'supply_id',  'gramprice_fee', 'label_price','pieceprice_fee', 'piece_weight', 'netglod_weight',  'costglod_price', 'costpiece_fee', 'costgram_fee','odds',
            'piececost_fee', 'goods_craft_id', 'gemstone_fee1', 'gemstone_fee2', 'add_fee1', 'add_fee2', 'goods_brand_id', 'cf_fee', 'main_stone_weigth', 'main_stone_count',
            'other_stone_weigth','other_stone_count',   'goods_pricetype_id', 'goods_stone_id', 'procure_at', 'paytype_id', 'paymoney'
        ];
        foreach ($infodata  as $key=>$val){
            if(in_array($key,$checkeys)){
                $infodata[$key]= empty($val)?0:$val;
            }
        }
//        $infodata['total_piece_weight'] = isset($infodata['total_piece_weight']) ? $infodata['total_piece_weight'] : 0;
//        $infodata['total_netglod_weight'] = isset($infodata['total_netglod_weight']) ? $infodata['total_netglod_weight'] : 0;
//        $infodata['goods_pricetype_id'] =empty($infodata['goods_pricetype_id'])? 0:$infodata['goods_pricetype_id'];
//        $infodata['goods_craft_id'] =empty($infodata['goods_craft_id'])? 0:$infodata['goods_craft_id'];
//        $infodata['goods_brand_id'] =empty($infodata['goods_brand_id'])? 0:$infodata['goods_brand_id'];
//        $infodata['goods_stone_id'] =empty($infodata['goods_stone_id'])? 0:$infodata['goods_stone_id'];
//        $infodata['label_price'] =empty($infodata['label_price'])? 0:$infodata['label_price'];
//        $infodata['piececost_fee'] =empty($infodata['piececost_fee'])? 0:$infodata['piececost_fee'];
//        $infodata['odds'] =empty($infodata['odds'])? 0:$infodata['odds'];
//        $infodata['costpiece_fee'] =empty($infodata['costpiece_fee'])? 0:$infodata['costpiece_fee'];
//        $infodata['costgram_fee'] =empty($infodata['costgram_fee'])? 0:$infodata['costgram_fee'];
//        $infodata['pieceprice_fee'] =empty($infodata['pieceprice_fee'])? 0:$infodata['pieceprice_fee'];
//        $infodata['pieceprice_fee'] =empty($infodata['pieceprice_fee'])? 0:$infodata['pieceprice_fee'];


        if ($req_data['is_code_more'] == 2) {
            //$infodata['total_cost_fee'] = bcmul((string)($infodata['costgram_fee'] + $infodata['costglod_price']), $infodata['total_netglod_weight'], 0) + $infodata['costpiece_fee'] * $infodata['count'];

            if ($infodata['total_netglod_weight'] <= 0) {
                return response()->json(['code' => '001', 'msg' => '一码多货必须输入总金重']);
            }
            $infodata['total_cost_fee'] = bcmul(($infodata['costglod_price'] ?? 0), ($infodata['total_netglod_weight'] ?? 0));

        } else {
            // 总件重
            $infodata['total_piece_weight'] = isset($infodata['piece_weight']) ? doubleval($infodata['piece_weight'] * $infodata['count']) : 0;
            // 总金重
            $infodata['total_netglod_weight'] = isset($infodata['netglod_weight']) ? doubleval($infodata['netglod_weight'] * $infodata['count']) : 0;
            $is_gram = GoodsCategory::where(['cp_id' => $cp_id, 'is_del' => 1, 'store_id' => $info->store_id, 'id' => $infodata['goods_category_id']])->value('is_gram');
            if ($is_gram == 1) {
                if ($infodata['total_netglod_weight'] <= 0 || $infodata['netglod_weight'] <= 0) {
                    return response()->json(['code' => '001', 'msg' => '总金重以及金重不可小于0']);
                }

                $infodata['total_cost_fee'] = bcmul((string)($infodata['costgram_fee'] + $infodata['costglod_price']), $infodata['total_netglod_weight'], 0) + $infodata['costpiece_fee'] * $infodata['count'];

            } else {
                if ($infodata['total_piece_weight'] < 0 || $infodata['piece_weight'] < 0) {
                    return response()->json(['code' => '001', 'msg' => '总件重以及件重不可小于0']);
                }

                $infodata['total_cost_fee'] = $infodata['piececost_fee'] * $infodata['count'];
            }


        }



        //处理数据类型
        DB::beginTransaction();
        try {
            $infodata['update_at'] = !empty($infodata)?time():0;
            //更新库存相关
            GoodsStockList::query()->where((['cp_id' => $cp_id, 'store_id' => $info->store_id, 'id' => $req_data['id'],'is_del' => 1]))
                ->update($infodata);

            $label_price_new = !empty($infodata['label_price']) ? $infodata['label_price'] : 0;
            $piece_weight_new = !empty($infodata['piece_weight']) ? $infodata['piece_weight'] : 0;
            $netglod_weight_new = !empty($infodata['netglod_weight']) ? $infodata['netglod_weight'] : 0;
            $total_piece_weight_new = !empty($infodata['total_piece_weight']) ? $infodata['total_piece_weight'] : 0;
            $total_netglod_weight_new = !empty($infodata['total_netglod_weight']) ? $infodata['total_netglod_weight'] : 0;

            GoodsStockinInfolist::query()->where(['order_sncode' => $info->order_sncode, 'goods_sn_code' => $info->goods_sn_code])->update([
                'label_price_new' => $label_price_new,
                'piece_weight_new' => $piece_weight_new,
                'netglod_weight_new' => $netglod_weight_new,
                'total_piece_weight_new' => $total_piece_weight_new,
                'total_netglod_weight_new' => $total_netglod_weight_new,
            ]);
            Log::info('order_sncode:' . $info->order_sncode . ' goods_sn_code:' . $info->goods_sn_code);
            Log::info('label_price_new:【' . $label_price_new . '】;piece_weight_new:【' . $piece_weight_new . '】;netglod_weight:【' . $netglod_weight_new . '】;total_piece_weight_new:【' . $total_piece_weight_new . '】;total_netglod_weight_new:【' . $total_netglod_weight_new . '】');

            $count = $infodata['count'] - $info->count;
            $infodata['stockin_at'] = $info->stockin_at;
            $infodata = GoodsStockList::where(['cp_id' => $cp_id, 'id' => $req_data['id'],'is_del' => 1])->first()->toArray();
            if((int)$infodata['count']== (int)$info->count){
                $log_type=4;
            }else{
                $log_type =$count > 0 ? 2 : 3;
            }
            Goods::goodsLog($request, 0, intval($info['store_id']), $infodata, intval($count), $log_type, '');

            Goods::changeGoodsLog($request, StoreCommon::createOrderSn(), $info->toArray(), json_encode($info->toArray()), json_encode($infodata));


            //增加日志相关
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '编辑商品入库失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '编辑商品入库成功']);
    }


    public function dopostinfoimgedit(Request $request)
    {

        $id = intval($request->id);
        $goods_img = $request->goods_img;


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = GoodsStockList::where(['cp_id' => $cp_id, 'id' => $id,'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }


        if ($goods_img == '') {
            return response()->json(['code' => '001', 'msg' => '请选择上传图片']);
        }

        $update_at= !empty($goods_img)?time():0;

        GoodsStockList::where(['cp_id' => $cp_id, 'id' => $id,'is_del' => 1])->update(['goods_img' => $goods_img,'update_at'=>$update_at]);

        return response()->json(['code' => '000', 'msg' => '商品图片补录成功']);
    }

    /**
     * 转旧料
     */
    public function transformoldmaterial(Request $request)
    {
        $id = intval($request->id);
        $count = intval($request->count);
        $weight = $request->weight;
        $remark = $request->remark;
        if ($id <= 0) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($count <= 0) {
            return response()->json(['code' => '001', 'msg' => '数量必须大于0']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsStockList::with(['goods_category'])->where(['cp_id' => $cp_id, 'id' => $id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->count < $count) {
            return response()->json(['code' => '001', 'msg' => '库存不足']);
        }


        if ($info->goods_category->is_gram == 1 && $info->total_netglod_weight < $weight) {
            return response()->json(['code' => '001', 'msg' => '库存总金重小于转旧料重量']);
        }

        $data = $info->toArray();
        //转旧料时，重量处理：$weight是总重量
        // 如果是克重那么重量=金重*数量
        // 如果是件重那么重量=件重*数量
        // 如果是一码多货那么重量=输入的金重
        if ($info->is_code_more == 2) {
            if ($weight < 0) {
                return response()->json(['code' => '001', 'msg' => '一码多货需要输入重量']);
            } else {
                $data['netglod_weight'] = $weight;
                $data['netglod_weight_new'] = $weight;
                $data['piece_weight'] = $data['netglod_weight'];
            }
        } else {
            $data['piece_weight'] = ($info->piece_weight ?? 0) * $count;
            $data['netglod_weight'] = ($info->netglod_weight ?? 0) * $count;
            $data['netglod_weight_new'] = $data['netglod_weight'];
            $data['piece_weight'] = $info->goods_category->is_gram == 1 ? $data['netglod_weight'] : $data['piece_weight'];

        }

        $old_recovery_price = 0;
        if ($info->goods_category->is_gram == 1) { //克算
            $lastprice = GoodsGlodprice::where(['cp_id' => $cp_id, 'store_id' => $info->store_id, 'goods_category_id' => $info->goods_category->id, 'is_del' => 1])
                ->where('date_str', '<=', date('Y-m-d'))->orderBy('date_str', 'desc')->first();

            $old_recovery_price = $lastprice ? $lastprice->back_company_price : 0;
        }

        $cp_id = $accountinfo['cp_id'];

        $data['remark'] = $remark;
        $data['count'] = $count;
        $data['stock_type'] = GoodsCategory::where(['cp_id' => $cp_id, 'id' => $info->goods_category_id])->value('is_gram');
        unset($data['allot_count']);
        unset($data['sales_count']);
        unset($data['id']);
        unset($data['start_stockin_store_id']);
        unset($data['is_del']);
        unset($data['del_at']);
        unset($data['pricetype']);
        unset($data['odds']);
        $data['type'] = 3;
        $data['create_at'] = time();
        $data['update_at'] = time();
        $data['create_account_id'] = $accountinfo['id'];
        $data['update_account_id'] = $accountinfo['id'];
        $data['create_account_real_name'] = $accountinfo['real_name'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        $data['back_company_price'] = $old_recovery_price;
        $data['valuations'] = ($data['piece_weight'] ?? 0) * $old_recovery_price;


        //处理数据类型
        DB::beginTransaction();
        try {
            //转旧料时，重量就是实重
            $data['piece_weight_new'] = $data['piece_weight'];
            $log = $info->toArray();

            $stock= $info->toArray();

            $info['count'] =$info['count']-$count;
            $log['count']=$count;
            if ($info->is_code_more == 2) {
                // 一码多货
                $info['total_netglod_weight']= $info['total_netglod_weight']-$weight;
                $log['total_netglod_weight']=$weight;
            } else {
                $log['total_netglod_weight']=$info->netglod_weight * $count;
                $log['total_piece_weight']=$info->piece_weight * $count;
                $info['total_netglod_weight']= $info->total_netglod_weight > 0?($info['total_netglod_weight']-($info->netglod_weight * $count)):0;
                $info['total_piece_weight']= $info->total_netglod_weight > 0?($info['total_piece_weight']-($info->piece_weight * $count)):0;
            }

            if($info['count']<0){
                return response()->json(['code' => '001', 'msg' => '该商品数量不能扣减为负值']);
            }

            list($deduct_total_cost_fee,$remaining_cost_fee)=(new Goods())->deductTotalCost($stock,$log);

            //$is_gram =$info->goods_category->is_gram;
            //$total_cost_fee =(new Goods())->computeOriginalTotalCost($info,$is_gram);


            $stockData=[
                'count'=>$info['count'],
                'total_netglod_weight'=>$info['total_netglod_weight']??0,
                'total_piece_weight'=>$info['total_piece_weight']??0,
                'total_cost_fee'=>$remaining_cost_fee
            ];
            $log['total_cost_fee']=$deduct_total_cost_fee;
            $data['total_cost_fee'] =$deduct_total_cost_fee;
            Stock::create($data);
            GoodsStockList::query()
                ->where((['cp_id' => $cp_id, 'id' => $id, 'is_del' => 1]))
                ->update($stockData);


            Goods::goodsLog($request, 0, intval($log['store_id']), $log, intval(-$count), 3, '');
            //增加日志相关
            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '转旧料操作失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '转旧料操作成功']);


    }

    public function doexport(Request $request)
    {

        $list = GoodsStockList::getList($request)['list'];
        $row = [
            [
                'storeinfo' => '所属门店',
                'goods_sn_code' => '条码',
                'goods_name' => '品名',
                'status' => '状态',
                'category_name' => '商品类别',
                'content' => '含量',
                'goods_craft_name' => '工艺',
                'goods_stone_name' => '石料材质',
                's_no' => '款号',
                'style_name' => '款式',
                'count' => '数量',
                'allot_count' => '调拨数量',
                'netglod_weight' => '金重',
                'netglod_weight_total' => '总金重',
                'piece_weight' => '重量',
                'piece_weight_total' => '总重量',
                'label_price' => '标签价',
                'brand_name' => '品牌',
                'gramprice_fee' => '克销工费',
                'piece_weight_total1' => '入库重量',
                'pieceprice_fee' => '件销工费',
                'costglod_price' => '成本金价',
                'costpiece_fee' => '按件成本工费',
                'costgram_fee' => '按克成本工费',
                'piececost_fee' => '单件成本',
                'total_cost_fee' => '总成本',
                'goods_pricetype_name' => '价格类型',
                'cf_no' => '证书号', //Z
                'cf_no_gia' => 'GIA证书号',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'c_no' => '圈号',
                'cf_fee' => '证书费',
                'gemstone_fee1' => '宝石费1',
                'gemstone_fee2' => '宝石费2',
                'add_fee1' => '附加费1',
                'add_fee2' => '附加费2',
                'color' => '颜色',
                'clarity' => '净度',
                'cut' => '切工',
                'startstoreinfo' => '初始入库门店',
                'is_code_more' => '一码多货',
                'stockin_at' => '库存时间',
                'remark' => '备注',
                'create_at' => '创建时间',
            ]];
        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[0]['costglod_price']);
            unset($row[0]['piececost_fee']);
            unset($row[0]['total_cost_fee']);
        }

        $exceldata = [];
        foreach ($list as $val) {
            $exceldata[] = [
                'storeinfo' => $val['storeinfo'] ? $val['storeinfo']['store_name'] : '',
                'goods_sn_code' => "{$val['goods_sn_code']} ",
                'goods_name' => $val['goods_name'],
                'status' => $val['count'] > 0 ? '在售' : '售出',
                'category_name' => $val['goods_category']['category_name'],
                'content' => isset($val['goods_content']['content_name']) ? $val['goods_content']['content_name'] : '',
                'goods_craft_name' => isset($val['goods_craft']['craft_name']) ? $val['goods_craft']['craft_name'] : '',
                'goods_stone_name' => isset($val['goods_stone']['goods_stone_name']) ? $val['goods_stone']['goods_stone_name'] : '',
                's_no' => $val['s_no'],
                'style_name' => isset($val['goods_style']['style_name']) ? $val['goods_style']['style_name'] : '',
                'count' => $val['count'],
                'allot_count' => $val['allot_count'],
                'netglod_weight' => $val['netglod_weight'],
                'netglod_weight_total' => $val['total_netglod_weight'],
                'piece_weight' => $val['piece_weight'],
                'piece_weight_total' => $val['piece_weight'] * $val['count'],
                'label_price' => $val['label_price'] / 100,
                'brand_name' => isset($val['goods_brand']['brand_name']) ? $val['goods_brand']['brand_name'] : '',
                'gramprice_fee' => $val['gramprice_fee'] / 100,
                'piece_weight_total1' => $val['piece_weight'] * $val['count'],
                'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                'costglod_price' => $val['costglod_price'] / 100,
                'costpiece_fee' => $val['costpiece_fee'] / 100,
                'costgram_fee' => $val['costgram_fee'] / 100,
                'piececost_fee' => $val['piececost_fee'] / 100,
                'total_cost_fee' => $val['total_cost_fee']>0? ($val['total_cost_fee'] / 100) :0,
                'goods_pricetype_name' => isset($val['goods_pricetype']['goods_pricetype_name']) ? $val['goods_pricetype']['goods_pricetype_name'] : '',
                'cf_no' => $val['cf_no'],
                'cf_no_gia' => $val['cf_no_gia'],
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'c_no' => $val['c_no'],
                'cf_fee' => $val['cf_fee'] / 100,

                'gemstone_fee1' => $val['gemstone_fee1'] / 100,
                'gemstone_fee2' => $val['gemstone_fee2'] / 100,

                'add_fee1' => $val['add_fee1'] / 100,
                'add_fee2' => $val['add_fee2'] / 100,
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'cut' => $val['cut'],
                'startstoreinfo' => $val['startstoreinfo'] ? $val['startstoreinfo']['store_name'] : '',
                'is_code_more' => $val['is_code_more'] == 1 ? '否' : '是',
                'stockin_at' => $val['stockin_at'] > 0 ? date('Y-m-d H:i:s', $val['stockin_at']) : '',
                'remark' => $val['remark'],
                'create_at' => date('Y-m-d', $val['create_at']),
            ];
        }

        $filename = '商品库存信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

}
